package model

import (
	"cloudmusic/config"
	"sync"
	"time"
)

type Music struct {
	Id        int64  `json:"id"`
	MusicName string `json:"music_name"`
	ossName   string
	Size      int64
	Type      string
	Lyric     string
	AlbumName string `json:"album_name"`
	Singer    string `json:"singer"`
}

type MusicListResult struct {
	List   []Music
	Expire int64
	lock   sync.RWMutex
}

var MusicList MusicListResult

func (music Music) GetOssName() string {
	return music.ossName
}
func (music *Music) SetOssName(ossName string) {
	music.ossName = ossName
}
func (music *Music) GetMusicById() (err error) {
	err = config.Db.QueryRow("SELECT ossName,type,lyric FROM music WHERE id = ?", music.Id).Scan(&music.ossName, &music.Type, &music.Lyric)
	return
}

func IncMusicPlayTimes(songId int64) (err error) {
	_, err = config.Db.Exec("UPDATE music SET playTimes=playTimes+1 WHERE id = ?", songId)
	return
}

func (music *Music) InsertOrUpdate() (err error) {
	_, err = config.Db.Exec("REPLACE INTO music(musicName,ossName,size,type,lyric,albumName,singer) VALUES (?,?,?,?,?,?,?)", music.MusicName, music.ossName, music.Size, music.Type, music.Lyric, music.AlbumName, music.Singer)
	return
}

func GetMusicList() (err error) {
	MusicList.List = nil
	row, err := config.Db.Query("SELECT id,musicName,albumName,singer FROM music")
	defer row.Close()
	if err == nil {
		MusicList.lock.RLock()
		for row.Next() {
			music := Music{}
			err = row.Scan(&music.Id, &music.MusicName, &music.AlbumName, &music.Singer)
			MusicList.List = append(MusicList.List, music)
		}
		MusicList.Expire = time.Now().Unix() + 7200
		MusicList.lock.RUnlock()
	}
	return
}
